package com.pqc.tbk.utils;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

import com.pqc.tbk.service.admin.BaseService;

/**
 * 
 * @author 赵龙, create on 2012-7-27 下午6:16:41
 * 
 * 
 */
public class PageUtil<T> {

	/**
	 * 转化搜索的内容返回Page对象
	 * 
	 * @param searchTo
	 * @param pageable
	 * @param condition
	 *            自己要额外添加的搜索条件
	 * @return
	 */
	public Page<T> searchPage(final JqGridSearchTo searchTo,
			final Pageable pageable, final String condition,
			final BaseService<T> baseService) {
		// 单个字段查询
		Page<T> page = null;
		if ((searchTo.getSearchField() != null)
				&& !"".equals(searchTo.getSearchField())) {
			page = baseService.getPage(searchTo.getSingleOperation(condition),
					pageable);
		} else { // 多个字段查询
			// 将json转换成JqGridSearchTo对象
			final JsonMapper mapper = JsonMapper.buildNonDefaultMapper();
			final JqGridSearchTo copy = mapper.fromJson(searchTo.getFilters(),
					JqGridSearchTo.class);
			// 将转换出来的内容重新赋值给searchTo
			// 注意searchTo中的内容要保存下来,因为要用到排序的东西
			// 如果直接赋值它里面本来的内容就已经被覆盖了
			searchTo.setGroupOp(copy.getGroupOp());
			searchTo.setRules(copy.getRules());
			// 根据搜索出来的条件进行查询
			page = baseService.getPage(searchTo.getMutiOperation(condition),
					pageable);
		}
		return page;
	}

	/**
	 * 组装pageable对象
	 * 
	 * @param cpage
	 *            当前页
	 * @param pageSize
	 *            每页的记录数
	 * @return
	 */
	public Pageable getPageable(final int cpage, final int pageSize) {

		final Pageable pageable = new Pageable() {

			@Override
			public Sort getSort() {
				return null;
			}

			@Override
			public int getPageSize() {
				return pageSize;
			}

			@Override
			public int getPageNumber() {
				if (cpage < 1) {
					return 1;
				} else {
					return cpage;
				}
			}

			@Override
			public int getOffset() {
				final int cpage = getPageNumber();
				return (cpage - 1) * pageSize;
			}
		};
		return pageable;
	}

}
